<template>
  <div class="standard-page">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <el-page-header :content="['质检管理', '质检标准管理']" />
      <el-button type="primary" icon="el-icon-plus" @click="openDialog(false)">新增标准</el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="100px" size="medium">
        <el-form-item label="物料群组">
          <el-select 
            v-model="searchForm.materialGroupId" 
            placeholder="全部" 
            clearable
            style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option 
              v-for="group in materialGroups" 
              :key="group.id" 
              :label="group.materialGroupName" 
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标准状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="全部" 
            clearable
            style="width: 150px;"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterStandards">查询</el-button>
          <el-button @click="resetSearch" style="margin-left: 8px;">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 标准列表 -->
    <el-card shadow="hover">
      <el-table 
        :data="filteredStandards" 
        border 
        stripe
        style="width: 100%;"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="materialGroupName" label="物料群组" width="200" />
        <el-table-column prop="passRateThreshold" label="合格率阈值(%)" width="160">
          <template #default="scope">
            {{ scope.row.passRateThreshold }}%
          </template>
        </el-table-column>
        <el-table-column prop="samplingRatio" label="抽样比例(%)" width="160">
          <template #default="scope">
            {{ scope.row.samplingRatio }}%
          </template>
        </el-table-column>
        <el-table-column prop="inspectionItems" label="检验项目" width="300">
          <template #default="scope">
            <el-tag 
              v-for="(item, index) in scope.row.inspectionItems.split(',').filter(Boolean)" 
              :key="index" 
              size="small"
              type="info"
              style="margin: 2px;"
            >
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="toggleStatus(scope.row)"
              active-color="#4CAF50"
              inactive-color="#f56c6c"
            />
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button link type="warning" @click="openDialog(true, scope.row)">编辑</el-button>
            <el-button link type="danger" @click="deleteStandard(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑质检标准' : '新增质检标准'" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="standardFormRef" 
        :model="standardForm" 
        :rules="standardRules" 
        label-width="120px"
        size="medium"
      >
        <el-form-item label="物料群组" prop="materialGroupId">
          <el-select 
            v-model="standardForm.materialGroupId" 
            placeholder="请选择" 
            :disabled="isEdit"
          >
            <el-option 
              v-for="group in materialGroups" 
              :key="group.id" 
              :label="group.materialGroupName" 
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合格率阈值(%)" prop="passRateThreshold">
          <el-input
            v-model.number="standardForm.passRateThreshold"
            placeholder="如95（表示95%）"
            min="0"
            max="100"
          />
          <div class="form-hint">低于该阈值的质检记录将被标记为异常</div>
        </el-form-item>
        <el-form-item label="抽样比例(%)" prop="samplingRatio">
          <el-input
            v-model.number="standardForm.samplingRatio"
            placeholder="如100（表示全检）"
            min="1"
            max="100"
          />
          <div class="form-hint">每次质检的抽样比例</div>
        </el-form-item>
        <el-form-item label="检验项目" prop="inspectionItems">
          <div class="tag-container">
            <el-tag
              v-for="(item, index) in standardForm.inspectionItemsList"
              :key="index"
              closable
              @close="removeItem(index)"
              style="margin: 5px;"
            >
              {{ item }}
            </el-tag>
          </div>
          <el-input
            v-model="newItem"
            placeholder="输入检验项目，按回车添加"
            @keyup.enter="addItem"
            style="width: 220px; margin-top: 10px;"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="standardForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

axios.defaults.baseURL = 'http://localhost:5046';
const pinia = useCounterStore();

// 筛选表单
const searchForm = reactive({
  materialGroupId: '',
  status: ''
});

// 物料群组列表（从质检API提取）
const materialGroups = ref<any[]>([]);

// 质检标准数据（存储在localStorage）
const standards = ref<any[]>([]);
const filteredStandards = ref<any[]>([]); // 筛选后的数据

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const standardFormRef = ref<FormInstance>();
const standardForm = reactive({
  id: 0,
  materialGroupId: '',
  materialGroupName: '',
  passRateThreshold: 95, // 默认95%
  samplingRatio: 100,    // 默认全检
  inspectionItemsList: [] as string[], // 检验项目列表
  inspectionItems: '',   // 检验项目字符串（逗号分隔）
  status: '1',           // 1-启用，0-禁用
  creator: pinia.piniaDto.realName || '未知用户',
  createTime: ''
});
const newItem = ref(''); // 新检验项目输入

// 表单验证规则
const standardRules = reactive<FormRules>({
  materialGroupId: [{ required: true, message: '请选择物料群组', trigger: 'change' }],
  passRateThreshold: [
    { required: true, message: '请输入合格率阈值', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '阈值必须在0-100之间', trigger: 'blur' }
  ],
  samplingRatio: [
    { required: true, message: '请输入抽样比例', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '比例必须在1-100之间', trigger: 'blur' }
  ],
  inspectionItemsList: [
    { 
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error('至少添加一个检验项目'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 从localStorage加载标准数据
const loadStandardsFromLocal = () => {
  const localData = localStorage.getItem('qualityStandards');
  if (localData) {
    standards.value = JSON.parse(localData);
  } else {
    // 初始化默认数据
    standards.value = [];
  }
  filterStandards(); // 初始化筛选
};

// 保存标准数据到localStorage
const saveStandardsToLocal = () => {
  localStorage.setItem('qualityStandards', JSON.stringify(standards.value));
  filterStandards();
};

// 筛选标准数据
const filterStandards = () => {
  filteredStandards.value = standards.value.filter((item) => {
    // 物料群组筛选
    if (searchForm.materialGroupId && item.materialGroupId !== searchForm.materialGroupId) return false;
    // 状态筛选
    if (searchForm.status && item.status !== searchForm.status) return false;
    return true;
  });
};

// 重置筛选条件
const resetSearch = () => {
  searchForm.materialGroupId = '';
  searchForm.status = '';
  filterStandards();
};

// 获取物料群组列表（从质检API提取）
const getMaterialGroups = async () => {
  try {
    const response = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
      params: { Index: 1, Size: 9999 }
    });
    if (response.data.code === 200) {
      const data = response.data.data.totalPage || [];
      const groupSet = new Set<any>();
      data.forEach((item: any) => {
        if (item.materialGroupId && item.materialGroupName) {
          groupSet.add({ id: item.materialGroupId, materialGroupName: item.materialGroupName });
        }
      });
      materialGroups.value = Array.from(groupSet);
    }
  } catch (error) {
    ElMessage.error('获取物料群组失败');
    console.error(error);
  }
};

// 打开弹窗
const openDialog = (edit: boolean, row?: any) => {
  isEdit.value = edit;
  dialogVisible.value = true;
  
  // 重置表单
  standardForm.id = 0;
  standardForm.materialGroupId = '';
  standardForm.materialGroupName = '';
  standardForm.passRateThreshold = 95;
  standardForm.samplingRatio = 100;
  standardForm.inspectionItemsList = [];
  standardForm.inspectionItems = '';
  standardForm.status = '1';
  standardForm.createTime = '';
  newItem.value = '';

  // 编辑模式：回填数据
  if (edit && row) {
    standardForm.id = row.id;
    standardForm.materialGroupId = row.materialGroupId;
    standardForm.materialGroupName = row.materialGroupName;
    standardForm.passRateThreshold = row.passRateThreshold;
    standardForm.samplingRatio = row.samplingRatio;
    standardForm.inspectionItemsList = row.inspectionItems.split(',').filter(Boolean);
    standardForm.inspectionItems = row.inspectionItems;
    standardForm.status = row.status;
    standardForm.creator = row.creator;
    standardForm.createTime = row.createTime;
  }
};

// 添加检验项目
const addItem = () => {
  if (!newItem.value.trim()) return;
  const item = newItem.value.trim();
  if (!standardForm.inspectionItemsList.includes(item)) {
    standardForm.inspectionItemsList.push(item);
  }
  newItem.value = '';
};

// 移除检验项目
const removeItem = (index: number) => {
  standardForm.inspectionItemsList.splice(index, 1);
};

// 提交表单（新增/编辑）
const submitForm = async () => {
  if (!standardFormRef.value) return;
  
  await standardFormRef.value.validate(async (valid) => {
    if (valid) {
      // 合并检验项目为字符串
      standardForm.inspectionItems = standardForm.inspectionItemsList.join(',');
      // 填充物料群组名称
      const group = materialGroups.value.find(g => g.id === standardForm.materialGroupId);
      if (group) {
        standardForm.materialGroupName = group.materialGroupName;
      }

      if (isEdit.value) {
        // 编辑：更新现有数据
        const index = standards.value.findIndex(item => item.id === standardForm.id);
        if (index !== -1) {
          standards.value[index] = { ...standards.value[index], ...standardForm };
          ElMessage.success('标准更新成功');
        }
      } else {
        // 新增：生成ID（时间戳）
        standardForm.id = Date.now();
        standardForm.createTime = new Date().toISOString();
        standards.value.push({ ...standardForm });
        ElMessage.success('标准新增成功');
      }

      // 保存到localStorage
      saveStandardsToLocal();
      dialogVisible.value = false;
    }
  });
};

// 切换启用/禁用状态
const toggleStatus = (row: any) => {
  const index = standards.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    standards.value[index].status = row.status;
    saveStandardsToLocal();
    ElMessage.success(`已${row.status === '1' ? '启用' : '禁用'}该标准`);
  }
};

// 删除标准
const deleteStandard = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除该质检标准吗？删除后无法恢复。',
    '删除确认',
    { type: 'warning' }
  ).then(() => {
    standards.value = standards.value.filter(item => item.id !== id);
    saveStandardsToLocal();
    ElMessage.success('标准删除成功');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 监听物料群组变化，自动填充名称
watch(() => standardForm.materialGroupId, (val) => {
  if (val && !isEdit.value) {
    const group = materialGroups.value.find(g => g.id === val);
    if (group) {
      standardForm.materialGroupName = group.materialGroupName;
    }
  }
});

// 页面初始化
onMounted(() => {
  getMaterialGroups();
  loadStandardsFromLocal();
});
</script>

<style scoped>
.standard-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.filter-card {
  margin-bottom: 16px;
  padding: 16px;
}
.tag-container {
  display: flex;
  flex-wrap: wrap;
}
.form-hint {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .filter-card .el-form {
    flex-direction: column;
    align-items: flex-start !important;
  }
  .filter-card .el-form-item {
    width: 100% !important;
    margin-bottom: 8px;
  }
}
</style>